/**
 * @FilePath: \ros2\src\tools\shared_parameters\src\include\shared_parameters\shared_memory_manager.hpp
 * @Description:  
 * @Author: haibo
 * @Version: 1.0.0
 * @LastEditors: haibo ashengzi@163.com
 * @LastEditTime: 2025-02-20 20:40:32
 * @Copyright (c) 2025 by 临工智能信息科技有限公司, All Rights Reserved. 
**/
#pragma once
#include "shared_parameters/shared_memory_interface.hpp"
#include "shared_parameters/log.hpp"
#include <memory>
#include <iostream>

class SharedMemoryManager {
public:
    static SharedMemoryManager& getInstance() {
        static SharedMemoryManager instance;
        return instance;
    }

    // 获取共享内存指针
    bip::managed_shared_memory* getSharedMemory() { return shm_.get(); }
    
    // 获取互斥锁指针
    bip::named_mutex* getMutex() { return mutex_.get(); }
    
    // 获取参数映射指针
    SharedData::ParamMap* getParamsMap() { return params_; }

    // 初始化共享内存（第一个进程调用）
    bool initializeSharedMemory() {
        try {
            DEBUG("Initializing shared memory...");
            
            // 创建共享内存
            shm_ = std::make_unique<bip::managed_shared_memory>(
                bip::create_only,
                SharedMemoryConfig::SHM_NAME,
                SharedMemoryConfig::SHM_SIZE
            );

            // 创建互斥锁
            mutex_ = std::make_unique<bip::named_mutex>(
                bip::create_only,
                SharedMemoryConfig::MUTEX_NAME
            );

            // 在共享内存中构造参数映射
            auto alloc = shm_->get_segment_manager();
            params_ = shm_->construct<SharedData::ParamMap>("params")
                (std::less<SharedData::SharedString>(), alloc);

            DEBUG("Shared memory initialized successfully");
            return true;
        } catch (const bip::interprocess_exception& ex) {
            DEBUG("Failed to initialize shared memory: %s", ex.what());
            return false;  // 已经存在
        }
    }

    // 连接到共享内存（其他进程调用）
    bool connectToSharedMemory() {
        try {
            DEBUG("Connecting to shared memory...");
            
            // 打开已存在的共享内存
            shm_ = std::make_unique<bip::managed_shared_memory>(
                bip::open_only,
                SharedMemoryConfig::SHM_NAME
            );

            // 打开已存在的互斥锁
            mutex_ = std::make_unique<bip::named_mutex>(
                bip::open_only,
                SharedMemoryConfig::MUTEX_NAME
            );

            // 查找参数映射
            params_ = shm_->find<SharedData::ParamMap>("params").first;
            
            if (!params_) {
                DEBUG("Failed to find params map in shared memory");
                return false;
            }

            DEBUG("Connected to shared memory successfully");
            return true;
        } catch (const bip::interprocess_exception& ex) {
            DEBUG("Failed to connect to shared memory: %s", ex.what());
            return false;
        }
    }

    // 清理共享内存（最后一个进程调用）
    static void cleanup() {
        try {
            bip::shared_memory_object::remove(SharedMemoryConfig::SHM_NAME);
            bip::named_mutex::remove(SharedMemoryConfig::MUTEX_NAME);
            DEBUG("Shared memory cleaned up");
        } catch (const std::exception& ex) {
            DEBUG("Error during cleanup: %s", ex.what());
        }
    }

    // 析构函数
    ~SharedMemoryManager() {
        try {
            if (shm_) {
                shm_.reset();
            }
            if (mutex_) {
                mutex_.reset();
            }
        } catch (const std::exception& ex) {
            DEBUG("Error during SharedMemoryManager destruction: %s", ex.what());
        }
    }

private:
    SharedMemoryManager() = default;
    SharedMemoryManager(const SharedMemoryManager&) = delete;
    SharedMemoryManager& operator=(const SharedMemoryManager&) = delete;

    std::unique_ptr<bip::managed_shared_memory> shm_;
    std::unique_ptr<bip::named_mutex> mutex_;
    SharedData::ParamMap* params_ = nullptr;
};